import datetime
from other.cfg import Config
from other.change_format import change_format
from other.sql_montage import sqlMontage
from other.status import Status
from server.Mysql import MySQL


class category:
    def __init__(self):
        self.cfg = Config()
        self.st = Status()
        self.db = MySQL(self.cfg.res['mysql']['database'], 'category')
        self.cf = change_format()
        self.sm = sqlMontage()

    # 获取分类列表
    def get_category_list(self, data):
        result = {'msg': '成功', 'code': 200, 'data': [], 'total': None}
        sqls = "where 1=1 "
        sql = ""
        if data != {}:
            if data.get('categoryName') is not None:
                if data['categoryName'] != '':
                    sql = sql + " and `category_name` like '%{}%'".format(data['categoryName'])
 
            if data.get('status') is not None:
                if data['status'] != '':
                    sql = sql + " and `status`='{}'".format(data['status'])
          
        total = self.db.get(sqls + sql)
        result['total'] = len(total)
        if sql != "":
            sql = sqls + sql + ' ORDER BY `order_num` ASC '
        else:
            sql = sqls + ' ORDER BY `order_num` ASC '
        res = self.db.get(sql)
        if res != ():
            for r in res:
                for key, value in r.items():
                    if isinstance(value, datetime.datetime):
                        r[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                result['data'].append(r)
        result = self.cf.changes_format(result)
        return result

    def get_category_tree_info(self, data):
         # 获取所有分类
        sql = " ORDER BY `order_num` ASC"
        categories = self.db.get(sql)
        
        # 初始化分类树
        category_tree = []
        looked = {}  # 用于记录已经添加到树中的分类

        for category in categories:
            parent_id = category['parent_id']
            node = {
                'id': category['category_id'],
                'name': category['category_name'],
                'children': []
            }
            if parent_id in looked:
                # 如果父分类已经存在于树中，则添加为子节点
                looked[parent_id]['children'].append(node)
            else:
                # 如果父分类不存在，则添加到树的根节点
                category_tree.append(node)
            # 记录当前分类
            looked[category['category_id']] = node

        return {'msg': '成功', 'code': 200, 'data': category_tree}

    # 新增分类
    def add_category(self, data,userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        g_sql = f"where `category_id`='{data['categoryId']}'"
        g_res = self.db.get(g_sql)
        if g_res != ():
            result['code'] = 500
            result['msg']= '分类名称重复'
        else:
            data['create_by'] = userInfo['userName']
            data['create_time'] = times 
            
            if data.get('parentId') is None:
                data['parentId'] = 0
            add_sql = self.sm.add_sql_data(data, 'category')
            self.db.adds(add_sql, 'category')
        return result
    

    # 修改分类
    def edit_category(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        g_sql = f"where `category_name`='{data['categoryName']}'"
        g_res = self.db.get(g_sql)
        ff = False
        if g_res != ():
            for g in g_res:
                if g['category_id'] == data['categoryId']:
                    ff = True
                else:
                    if g['category_name'] == data['categoryName']:
                        result['msg'] = '分类名称重复'
                    ff = False
                    result['code'] = 500
                    break
        else:
            ff = True
        if ff:
            data['update_by'] = userInfo['userName']
            data['update_time'] = times
            edit_sql = self.sm.edit_sql_data(data, 'category', 'category_id', data['categoryId'])
            self.db.edits(edit_sql, 'category')
        return result


    # 删除分类
    def del_category(self, data,userInfo):
        result = {'msg': '成功', 'code': 200}
        ids = [int(x) for x in data.split(',')]
        for i in ids:
            # 删除
            sql = "where category_id='{}'".format(i)
            self.db.delete(sql)
        return result
